package com.lry.basic.algorithm.flow.counter;

import java.util.concurrent.atomic.LongAdder;

//限制1s内过n个请求
//临界点问题
public class Counter {

    private int limit;

    private LongAdder reqCount = new LongAdder();

    private long interval  = 1000;

    private long expires = System.currentTimeMillis() + interval;


    public boolean canPass(){

        long now = System.currentTimeMillis();

        //如果当前时间小于过期时间点，则代表可以进去加数量，因为是这一秒的时钟周期
        if(now < expires){
            reqCount.increment();
            return reqCount.intValue()<=limit;
        }else{
            //否则，重置过期时间点，重置请求数量，本次直接成功
            expires = System.currentTimeMillis() + interval;
            reqCount.reset();
            reqCount.increment();
            return true;
        }
    }

    public Counter(int limit) {
        this.limit = limit;
    }
}
